<?php
/**
 * This is a controller for Page.
 *
 * This controller would be responsible for applying actions in classical admin area.
 * it could be any changes concerned mass applying
 */

class Backend_SwfuploaderController extends RCMS_Core_BaseController {

    /**
     * the path for saves preview image
     * @var string
     */
    private $_savePathPreviewImage;

    /**
     * a name of current theme
     * @var string
     */
    private $_currentTheme;

    /**
     * Special parser that creates seo for this site.
     * @var RCMS_Object_Parser_SeoParser
     */
    protected $_seoParser = null;

    /**
     * Preview path for page's image
     * @var string
     */
    protected $_savePathPreviewPage;

    public function init()
    {
        parent::init();
        $this->_pageModel = new Default_Model_PageModel();
        $this->_seoParser = new RCMS_Object_Parser_SeoParser();        
        $this->_savePathPreviewPage = $this->_config->website->website->path . 'public/tmp/';
        $this->_thingsModel = new Default_Model_ThingsModel();
        $this->_templateModel = new Default_Model_TemplateModel();
        $this->_currentTheme = $this->_templateModel->selectCurrentTheme();
        if($this->_currentTheme == '') {
            $this->_currentTheme = 'default';
        }
        $this->_savePathPreviewImage = $this->_config->website->website->path . 'public/themes/' . $this->_currentTheme . '/images/templatepreview/';
    }

    /**
     * upload image for current page
     * @return void
     */
    public function uploadpageAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $file = new Zend_File_Transfer_Adapter_Http();
        $data = $file->getFileInfo();        
        $mas = explode('.',$file->getFileName());
        $typeFile = $mas[count($mas)-1];
        $nameFile = strtolower(time() . '.' .$typeFile);
        $file->addValidator('Extension', false, 'jpg,png,gif');
        $file->addFilter('Rename',
            array('source' => $data['Filedata']['tmp_name'],
                  'target' => $this->_savePathPreviewPage . $nameFile,
                  'overwrite' => true));
        if($file->isUploaded() && $file->isValid())
        {
            $width = '';
           // $cropFlag = false;
            $file->setDestination($this->_savePathPreviewPage);
            try {                
                $file->receive();
                if($this->_pageModel->selectValueFromConfig('page_teaser_size')){
                    $width = (int)$this->_pageModel->selectValueFromConfig('page_teaser_size')->value;
                } else {
                    $width = RCMS_Object_QuickConfig_QuickConfig::$pagePreviewImage;
                }
				
              /*  if($this->_pageModel->selectValueFromConfig('page_image_crop')){
                    $cropFlag = $this->_pageModel->selectValueFromConfig('page_image_crop')->value;                 
                } else {
                    $cropFlag = unserialize(Zend_Registry::get('config'))->page->page->image_crop;
                }*/
                /*if($cropFlag) {
                    RCMS_Tools_Tools::resizeImage($this->_savePathPreviewPage . $nameFile, $width, $width);
                } else {*/
                    RCMS_Tools_Tools::cropImage($width, $width, $this->_savePathPreviewPage . $nameFile,$this->_savePathPreviewPage . $nameFile);
                //}
                echo $nameFile;
            }
            catch (Zend_File_Transfer_Exception $e) {
                echo $e->getMessage();
            }
        }
        unset($file);
    }

    /**
     * Upload image (ajax)
     * @return void
     */
    public function uploadtemplateAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $file = new Zend_File_Transfer_Adapter_Http();
        $data = $file->getFileInfo();        
        $mas = explode('.',$file->getFileName());
        $typeFile = $mas[count($mas)-1];
        $nameFile = strtolower(time() . '.' .$typeFile);
        $file->addValidator('Extension', false, 'jpg,png,gif');
        $file->addFilter('Rename',
            array('source' => $data['Filedata']['tmp_name'],
                  'target' => $this->_savePathPreviewImage . $nameFile,
                  'overwrite' => true));         
        if($file->isUploaded() && $file->isValid()) {
            $file->setDestination($this->_savePathPreviewImage);
            try {
                $file->receive();
                $width = 125;
                $height = 222;                
                RCMS_Tools_Tools::resizeImage($this->_savePathPreviewImage . $nameFile, $width, $height, true);
                echo $nameFile;
            }
            catch (Zend_File_Transfer_Exception $e) {
                echo $e->getMessage();
            }
        }
        unset($file);
    }

    /**
     * Uploads image.
     * @return void
     */
    public function uploadimagesAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $folderName = $this->getRequest()->getParam('folder');
        $folderName = RCMS_Tools_FilesystemTools::validateName($folderName);
        if($folderName == '') {
            echo json_encode(array('folder' => '')); exit;
        }
        $savePath = $this->_config->website->website->path . $this->_config->website->website->images;
        $flag = RCMS_Tools_FilesystemTools::mkDir($savePath . $folderName);
        if($flag) {
            RCMS_Tools_FilesystemTools::mkDir($savePath . $folderName . '/small');
            RCMS_Tools_FilesystemTools::mkDir($savePath . $folderName . '/medium');
            RCMS_Tools_FilesystemTools::mkDir($savePath . $folderName . '/large');
            RCMS_Tools_FilesystemTools::mkDir($savePath . $folderName . '/original');
            RCMS_Tools_FilesystemTools::mkDir($savePath . $folderName . '/video');
        }
        $fileName = strtolower(basename($_FILES['Filedata']['name']));
        if(preg_match("/\.(avi|mov|mp4|swf|flv|mpeg|wmv|mpg)$/", $fileName)) {
            $this->_saveFileInFileSystem($savePath, $folderName);
        }
        if(preg_match("/\.(gif|png|jpg)$/", $fileName)) {
            $this->_saveImageInFileSystem($savePath, $folderName);
        }
        echo json_encode(array('folder' => $folderName)); exit;
    }

    /**
     * Uploads file.
     * @return void
     */
    public function uploadfilesAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $file = new Zend_File_Transfer_Adapter_Http();
        $data = $file->getFileInfo();        
        $fileName = basename($file->getFileName());
        $array = explode('.', $fileName);
        $typeFile = $array[count($array)-1];
        unset($array[count($array)-1]);
        $fileName = RCMS_Tools_FilesystemTools::validateName(implode('', $array));
        $fileName = $fileName . '.' . strtolower($typeFile);
        $savePath = $this->_config->website->website->path . $this->_config->website->website->downloads;
        $file->addValidator('Extension', false, 'zip,rar,gif,png,jpg,avi,wmv,mov,pdf,mpg,mp4,swf,fla,doc,xsl,txt,ppf,exe,mp3,wav,ttf,ogg,tiff,gom,flv');
        $file->addFilter('Rename',
            array('source' => $data['Filedata']['tmp_name'],
                  'target' => $savePath . $fileName,
                  'overwrite' => true));
        if($file->isUploaded() && $file->isValid()) {
            $file->setDestination($savePath);
            try {
                $file->receive();
                unset($file);
                echo json_encode(array('file' => $fileName)); exit;
            }
            catch (Zend_File_Transfer_Exception $e){}
        }
    }

    /**
     * Saves image in filesysytem.
     * @param string $savePath
     * @param string $folderName
     * @return void
     */
    private function _saveImageInFileSystem($savePath, $folderName)
    {
        $file = new Zend_File_Transfer_Adapter_Http();
        $data = $file->getFileInfo();        
        $fileName = basename($file->getFileName());
        $array = explode('.', $fileName);
        $fileType = $array[count($array)-1];
        unset($array[count($array)-1]);
        $fileName = RCMS_Tools_FilesystemTools::validateName(implode('', $array));
        $fileName = $fileName.'.'.strtolower($fileType);
        $file->addValidator('Extension', false, 'jpg,png,gif');
        $file->addFilter('Rename',
            array('source' => $data['Filedata']['tmp_name'],
                  'target' => $savePath . $folderName . '/original/' . $fileName,
                  'overwrite' => true));
        
        if($file->isUploaded() && $file->isValid()) {
            $file->setDestination($savePath.$folderName.'/original/');
            try {
                $file->receive();
                
                if ($file->isReceived()) {
                    unset ($file);
                    $configWidthImage = $this->_thingsModel->selectConfigForImage();
                    $widthImageSmall = intval($configWidthImage['img_small']['value']);
                    $widthImageMedium = intval($configWidthImage['img_medium']['value']);
                    $widthImageLarge = intval($configWidthImage['img_large']['value']);
                    $widthMaxImage = intval($configWidthImage['img_max_width']['value']);
                    $infoImg = getimagesize($savePath.$folderName.'/original/'.$fileName);
                    
                    if(intval($infoImg[0]) > $widthMaxImage) {
                        RCMS_Tools_Tools::resizeImage($savePath.$folderName.'/original/'.$fileName, $widthMaxImage, 0, true, true);
                    }
                    
                    if (copy($savePath.$folderName.'/original/'.$fileName, $savePath.$folderName.'/small/'.$fileName)) {
                        $smallInfo = getimagesize($savePath.$folderName.'/small/'.$fileName);
                        if (intval($smallInfo[0]) > $widthImageSmall) {
                            RCMS_Tools_Tools::resizeImage($savePath.$folderName.'/small/'.$fileName, $widthImageSmall, 0, true);
                        }
                    }
                    
                    if(copy($savePath.$folderName.'/original/'.$fileName, $savePath.$folderName.'/medium/'.$fileName)) {
                        $mediumInfo = getimagesize($savePath.$folderName.'/medium/'.$fileName);
                        if (intval($mediumInfo[0]) > $widthImageMedium) {
                            RCMS_Tools_Tools::resizeImage($savePath.$folderName.'/medium/'.$fileName, $widthImageMedium, 0, true);
                        }
                    }                    
                    
                    if(copy($savePath.$folderName.'/original/'.$fileName, $savePath.$folderName.'/large/'.$fileName)) {
                        $largeInfo = getimagesize($savePath.$folderName.'/large/'.$fileName);
                        if (intval($largeInfo[0]) > $widthImageLarge) {
                            RCMS_Tools_Tools::resizeImage($savePath.$folderName.'/large/'.$fileName, $widthImageLarge, 0, true);
                        }
                    }
                }
            }
            catch (Zend_File_Transfer_Exception $e) { }
        }
    }

    /**
     * Saves file in filesystem.
     * @param string $path
     * @param string $folder
     * @return void
     */
    private function _saveFileInFileSystem($path, $folder)
    {
        $file = new Zend_File_Transfer_Adapter_Http();
        $data = $file->getFileInfo();        
        $fileName = basename($file->getFileName());
        $array = explode('.', $fileName);
        $fileType = $array[count($array)-1];
        unset($array[count($array)-1]);
        $fileName = RCMS_Tools_FilesystemTools::validateName(implode('', $array));
        $fileName = $fileName . '.' . strtolower($fileType);
        $file->addValidator('Extension', false, 'avi,mov,mp4,swf,flv,mpeg,wmv,mpg');
        $file->addFilter('Rename',
            array('source' => $data['Filedata']['tmp_name'],
                  'target' => $path . $folder . '/video/' . $fileName,
                  'overwrite' => true));
        if($file->isUploaded() && $file->isValid()) {
            $file->setDestination($path . $folder . '/video/');
            try {                
                    $file->receive();
                }
            catch (Zend_File_Transfer_Exception $e) {}
        }
        unset($file);
    }

    /**
     * Uploads image in gellery.
     * @return void
     */
    public function uploadimageingalleryAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $path = $this->_config->website->website->path . $this->_config->website->website->galleries;
        $gallery = $this->getRequest()->getParam('gallery');
        $gallery = RCMS_Tools_FilesystemTools::validateName(trim($gallery));        
        if($gallery == '' || !is_dir($path . $gallery)) {
            return;
        }
        $file = new Zend_File_Transfer_Adapter_Http();
        $data = $file->getFileInfo();
        $fileName = basename($file->getFileName());
        $array = explode('.', $fileName);
        $fileType = strtolower($array[count($array)-1]);
        unset ($array[count($array)-1]);
        $fileName = RCMS_Tools_FilesystemTools::validateName(implode('', $array));
        $fileName = $fileName.'.'.$fileType;
        $file->addValidator('Extension', false, 'jpg,png,gif');
        $file->addFilter('Rename',
            array('source' => $data['Filedata']['tmp_name'],
                  'target' => $path . $gallery . '/' . $fileName,
                  'overwrite' => true));
        if($file->isUploaded() && $file->isValid()) {
            $file->setDestination($path . $gallery);
            try {
                $file->receive();
                if (is_file($path.$gallery.'/'.$fileName)) {
                    $configWidthImage = $this->_thingsModel->selectConfigForImage();
                    $widthMaxImage = $configWidthImage['img_max_width']['value'];
                    $infoImg = getimagesize($path.$gallery.'/'.$fileName);
                    
                    if ($infoImg[0] > $widthMaxImage) {
                        RCMS_Tools_Tools::resizeImage($path.$gallery.'/'.$fileName, $widthMaxImage, 0, true,true);
                    }
                    if (copy($path.$gallery.'/'.$fileName, $path.$gallery.'/thumbnails/'.$fileName)) {
                        $settings = explode(':', @file_get_contents($path.$gallery.'/settings.txt'));

                        if ($settings[1] == 1) {
                            $imageFile = $path.$gallery.'/thumbnails/'.$fileName;

                            switch ($infoImg['mime']) {
                            case 'image/jpeg':
                                $image = imagecreatefromjpeg($imageFile);
                                break;
                            case 'image/png':
                                $image = imagecreatefrompng($imageFile);
                                break;
                            case 'image/gif':
                                $image = imagecreatefromgif($imageFile);
                                break;
                            default:
                                break;
                            }
                            $w = imagesx($image);
                            $h = imagesy($image);
                            $src_x = 0;
                            $src_y = 0;
                            if($w > $h) {
                                $min = $h;
                                $src_x = ceil(($w-$h)/2);
                            }
                            if($h > $w) {
                                $min = $w;
                                $src_y = ceil(($h-$w)/2);
                            }

                            $newImage = imagecreatetruecolor($min, $min);
                            imagecopy($newImage, $image, 0, 0, $src_x, $src_y, $w, $h);
                            switch ($infoImg['mime']) {
                                case 'image/jpeg':
                                    imagejpeg($newImage, $imageFile, RCMS_Object_QuickConfig_QuickConfig::$imageQuality);
                                    break;
                                case 'image/png':
                                    imagepng($newImage, $imageFile, 9);
                                    break;
                                case 'image/gif':
                                    imagegif($newImage, $imageFile);
                                    break;
                            }
                            imagedestroy($newImage);
                            RCMS_Tools_Tools::resizeImage($imageFile, $settings[0], 0, true);
                        } else {
                            RCMS_Tools_Tools::resizeImage($path.$gallery.'/thumbnails/'.$fileName, $settings[0], 0, true);
                        }
                    }
                } }
            catch (Zend_File_Transfer_Exception $e) {}
        }
        unset($file);       
    }
}
